package com.uum.admin.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uum.admin.dto.UserAuthDTO;
import com.uum.admin.pojo.entity.SysMenu;
import com.uum.admin.pojo.entity.SysPermission;
import com.uum.admin.pojo.entity.SysUser;
import com.uum.admin.pojo.query.UserPageQuery;
import com.uum.admin.service.*;
import com.uum.common.core.annotation.Operation;
import com.uum.common.core.constant.GlobalConstants;
import com.uum.common.core.constant.RedisConstants;
import com.uum.common.core.enums.BusinessType;
import com.uum.common.core.valid.InsertGroup;
import com.uum.common.core.valid.UpdateGroup;
import com.uum.common.core.result.Result;
import com.uum.web.exception.BizException;
import com.uum.web.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService sysUserService;
    private final SysMenuService sysMenuService;
    private final SysPermissionService sysPermissionService;
    private final RedisTemplate redisTemplate;

    @ApiOperation(value = "根据用户名获取用户信息")
    @GetMapping("/username/{username}")
    public Result<UserAuthDTO> getUserByUsername(@PathVariable String username) {
        UserAuthDTO userAuthDTO = sysUserService.getUserByUsername(username);
        return Result.success(userAuthDTO);
    }

    @ApiOperation(value = "后台-获取当前登陆的用户信息")
    @GetMapping("/getUserInfo")
    public Result<SysUser> getAdminUserInfo() {
        Long userId = JwtUtils.getUserId();
        String userInfoKey = RedisConstants.USER_INFO_KEY + userId;
        if (redisTemplate.hasKey(userInfoKey)) {
            Map resultMap = redisTemplate.opsForHash().entries(userInfoKey);
            return Result.success().add(resultMap);
        } else {
            //用戶信息
            SysUser userInfo = sysUserService.getUserInfoByUserId(userId);
            //根据用户的角色ID查询相应的菜单列表
            List<SysMenu> menuList = sysMenuService.listMenuByUserRoleId(userInfo.getRoleIds());
            //按钮权限
            List<String> permissionList = sysPermissionService.listPermissionByRoleIds(userInfo.getRoleIds()).stream().filter(item -> StrUtil.isNotBlank(item.getBtnPerm())).map(SysPermission::getBtnPerm).collect(Collectors.toList());
            Map<String,Object> infoMap = new HashMap<>();
            infoMap.put("userInfo",userInfo);
            infoMap.put("menuList",menuList);
            infoMap.put("permissionList",permissionList);
            redisTemplate.opsForHash().putAll(userInfoKey, infoMap);
            return Result.success().add(infoMap);
        }

    }

    @ApiOperation(value = "门户-获取当前登陆的用户信息")
    @GetMapping("/getDoorUserInfo")
    public Result<SysUser> getDoorUserInfo() {
        SysUser userInfo = sysUserService.getUserInfoByUserId(JwtUtils.getUserId());
        return Result.success(userInfo);
    }

    @Operation(description = "查询用户列表",businessType = BusinessType.QUERY,isSaveResponseData = false)
    @ApiOperation(value = "用户列表")
    @GetMapping("page")
    public Result pageUser(UserPageQuery userPageQuery) {
        IPage iPage = sysUserService.pageUser(userPageQuery);
        return Result.success(iPage.getRecords(), iPage.getTotal());
    }

    @ApiOperation(value = "用户详情")
    @GetMapping("detail")
    public Result userDetail(@RequestParam("id") Long id) {
        SysUser user = sysUserService.getUserInfoByUserId(id);
        return Result.success(user);
    }

    @Operation(description = "添加用户",businessType = BusinessType.INSERT)
    @ApiOperation(value = "添加用户")
    @PostMapping("add")
    public Result addUser(@Validated(InsertGroup.class) @RequestBody SysUser user) {
        sysUserService.addUser(user);
        return Result.success();
    }

    @Operation(description = "更新用户",businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新用户")
    @PutMapping("update")
    public Result updateUser(@Validated(UpdateGroup.class) @RequestBody SysUser user) {
        sysUserService.updateUser(user);
        return Result.success();
    }

    @Operation(description = "禁用用户",businessType = BusinessType.UPDATE)
    @ApiOperation(value = "禁用用户")
    @PutMapping("disabled")
    public Result disabledUser(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        boolean result = sysUserService.disabledUser(id,status);
        return Result.judge(result);
    }


    @Operation(description = "删除用户",businessType = BusinessType.DELETE)
    @ApiOperation(value = "完全删除用户")
    @DeleteMapping("delete/{ids}")
    public Result completeDeleteUser(@PathVariable("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        if (idList.contains(String.valueOf(JwtUtils.getUserId()))) {
            throw new BizException("不允许删除自身账号");
        }
        sysUserService.completeDeleteBatch(idList);
        return Result.success();
    }

}

